package com.utils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class HttpUtil {

	private static final String LOG_TAG = "HttpUtil";

	public static String getData(Map<String, String> map)
			throws UnsupportedEncodingException {
		if(map.isEmpty()){
			return "";
		}
		StringBuffer buffer = new StringBuffer();
		Iterator<String> ite = map.keySet().iterator();
		while (ite.hasNext()) {
			String key = ite.next();
			String value = map.get(key);
			buffer.append(key);
			buffer.append("=");
			buffer.append(URLEncoder.encode(value+"", "utf-8"));
			if (ite.hasNext()) {
				buffer.append("&");
			}
		}
		return buffer.toString();
	}

	public static String getDataWithoutEncoder(Map<String, String> map)
			throws UnsupportedEncodingException {
		StringBuffer buffer = new StringBuffer();
		Iterator<String> ite = map.keySet().iterator();
		while (ite.hasNext()) {
			String key = ite.next();
			String value = map.get(key);
			buffer.append(key);
			buffer.append("=");
			buffer.append(value);
			if (ite.hasNext()) {
				buffer.append("&");
			}
		}
		return buffer.toString();
	}
	
	public static String getSign(Map<String, String> map)
			throws UnsupportedEncodingException, NoSuchAlgorithmException {
		List<String> list = new ArrayList<String>();

		Iterator<String> ite = map.keySet().iterator();
		while (ite.hasNext()) {
			StringBuffer buffer = new StringBuffer();
			String key = ite.next();
			String value = map.get(key);
			buffer.append(key);
			buffer.append("=");
			buffer.append(value);
			list.add(buffer.toString());
		}

		Collections.sort(list);
		StringBuffer bf = new StringBuffer();
		for (String param : list) {
			bf.append(param); // 将参数键值对，以字典序升序排列后，拼接在一起
		}
		bf.append("$tr34@3wFG5^&w"); // 追加秘钥
		System.out.println(bf);
		String encode = URLEncoder.encode(bf.toString(), "UTF-8");

		return encode;
	}
	
	
	public static String postMsg(String data, String serverUrl,String currentTime) throws IOException{

		String callback = null;
		URL url = null;
		OutputStream outputStream = null;
		InputStream inputStream = null;
		HttpURLConnection httpUrlConnection = null;
		url = new URL(serverUrl);
		httpUrlConnection = (HttpURLConnection) url.openConnection();

		httpUrlConnection.setRequestMethod("POST");
		httpUrlConnection.setDoInput(true);
		httpUrlConnection.setDoOutput(true);
		httpUrlConnection.setUseCaches(false);
		httpUrlConnection.setRequestProperty("Charset", "UTF-8");
		httpUrlConnection.setRequestProperty("random", ""+currentTime);
		httpUrlConnection.setRequestProperty("User-Agent",
				"UltraMeAndroidClient");
		httpUrlConnection.setConnectTimeout(10 * 1000);
		httpUrlConnection.setReadTimeout(10 * 1000);

		if (data != null) {
			outputStream = httpUrlConnection.getOutputStream();
			outputStream.write(data.getBytes());
		}

		inputStream = httpUrlConnection.getInputStream();
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				inputStream, "utf-8"));
		StringBuilder buffer = new StringBuilder();
		String line = null;
		while ((line = reader.readLine()) != null) {
			buffer.append(line);
			buffer.append("");
		}
		callback = buffer.toString();
		if (outputStream != null) {
			outputStream.close();
			outputStream = null;
		}

		if (inputStream != null) {
			inputStream.close();
			inputStream = null;
		}
		if (httpUrlConnection != null) {
			httpUrlConnection.disconnect();
			httpUrlConnection = null;
		}
		return callback;
	}
	
	public static String postMsg(String data, String serverUrl)
			throws IOException {
		return postMsg(data, serverUrl, ""+System.currentTimeMillis());
	}

	public static String getMsg(String serverUrl) throws IOException {


		String callback = "";
		URL url = null;
		InputStream inputStream = null;
		HttpURLConnection httpUrlConnection = null;
		url = new URL(serverUrl);
		httpUrlConnection = (HttpURLConnection) url.openConnection();

		httpUrlConnection.setRequestMethod("GET");
		httpUrlConnection.setDoInput(true);
		httpUrlConnection.setUseCaches(false);
		httpUrlConnection.setRequestProperty("User-Agent",
				"UltraMeAndroidClient");
		httpUrlConnection.setConnectTimeout(30 * 1000);
		httpUrlConnection.setReadTimeout(30 * 1000);

		int responseCode = httpUrlConnection.getResponseCode();
		if (responseCode != 200) {
			return null;
		}
		inputStream = httpUrlConnection.getInputStream();
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				inputStream, "utf-8"));
		StringBuilder buffer = new StringBuilder();
		String line = null;
		while ((line = reader.readLine()) != null) {
			buffer.append(line);
			buffer.append("");
		}
		callback = buffer.toString();
		if (inputStream != null) {
			inputStream.close();
			inputStream = null;
		}
		if (httpUrlConnection != null) {
			httpUrlConnection.disconnect();
			httpUrlConnection = null;
		}
		return callback;
	}

	public static void downloadFile(String serverUrl, String savePath) {

		try {
			URL url = new URL(serverUrl);
			HttpURLConnection httpUrlConnection = (HttpURLConnection) url
					.openConnection();
			httpUrlConnection.setRequestMethod("GET");
			httpUrlConnection.setDoInput(true);
			httpUrlConnection.setDoOutput(true);
			httpUrlConnection.setUseCaches(false);
			httpUrlConnection.setRequestProperty("Charset", "UTF-8");
			httpUrlConnection.setConnectTimeout(10 * 1000);
			InputStream inputStream = httpUrlConnection.getInputStream();
			File file = new File(savePath);
			FileOutputStream fis = new FileOutputStream(file);
			BufferedInputStream bis = new BufferedInputStream(inputStream);
			byte[] buffer = new byte[1024];
			bis.read(buffer);
			int ch = -1;
			while ((ch = bis.read(buffer)) != -1) {
				fis.write(buffer, 0, ch);
			}
			if (fis != null) {
				fis.close();
				fis = null;
			}
			if (inputStream != null) {
				inputStream.close();
				inputStream = null;
			}
			if (httpUrlConnection != null) {
				httpUrlConnection.disconnect();
				httpUrlConnection = null;
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
